package com.zbl.zblproject.pay.controller;


import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.zbl.zblproject.core.entity.AdminUser;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.pay.entity.WXPayClient;
import com.zbl.zblproject.pay.entity.WeixinProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/12/12
 */
@Component
public class PayComponent {

    @Autowired
    public WeixinProperties weiProperties;

    private static Logger logger = LoggerFactory.getLogger(PayComponent.class);

    /**
     * 获取微信的API
     *
     * @param adminUser
     * @return
     */
    public WXPayClient getWXPayClientByAdminUser(AdminUser adminUser) throws Exception {
        //todo 微信
        if (adminUser == null) {
            throw new RuntimeException("用户未登录");
        }

        WeixinProperties properties = new WeixinProperties();
        properties.setAppID(weiProperties.getAppID());
        properties.setMchID(weiProperties.getMchID());
        properties.setKey(weiProperties.getKey());
        properties.setUseSandbox(weiProperties.getUseSandbox());
        properties.setSubMchId(weiProperties.getSubMchId());
        if (properties.getUseSandbox()) {
            //使用沙箱模式 请求沙箱模式KEY
            //todo key出现错误
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("mch_id", weiProperties.getMchID());
            requestBody.put("nonce_str", WXPayUtil.generateNonceStr());
            String sign = WXPayUtil.generateSignature(requestBody, properties.getKey(), WXPayConstants.SignType.MD5);
            requestBody.put("sign", sign);
            String xml = WXPayUtil.mapToXml(requestBody);
            RestTemplate restTemplate = new RestTemplate();
            logger.info("response body: {}", xml);
            String response =
                    restTemplate.postForObject("https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey", xml, String.class);
            Map<String, String> result = WXPayUtil.xmlToMap(response);
            properties.setKey(result.get("sandbox_signkey"));
            logger.info("回调 : {}", response);
            logger.info("微信 sandbox_signkey: {}", properties.getSandboxKey());
        }
        properties.setHttpConnectTimeoutMs(weiProperties.getHttpConnectTimeoutMs());
        properties.setHttpReadTimeoutMs(weiProperties.getHttpReadTimeoutMs());
        properties.setNotifyUrl(weiProperties.getNotifyUrl());

        return new WXPayClient(properties, WXPayConstants.SignType.MD5, properties.getUseSandbox());
    }


}
